package com.one.interceptor;

import com.one.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
*  JWT令牌拦截器
* */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    // 目标资源方法运行前执行,返回true表示放行，false表示拦截请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        try{
            Claims claims=JwtUtil.parseJWT("oneoneone", token);
            // TODO 记录token中数据
        }catch (Exception e){
            log.error("令牌解析异常: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); //设置401状态码
            return false; // 拦截请求
        }
        return true; // 继续处理请求
    }

    // 目标资源方法运行后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {

    }


    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
